import { Component, Input, Output, EventEmitter, OnInit, OnChanges } from '@angular/core';
import { NzNotificationService } from 'ng-zorro-antd';
import { Router } from '@angular/router';
import { HttpServcie } from '../../../../service/http.service';
import { Config } from '../../../../service/config';
import { el } from "@angular/platform-browser/testing/src/browser_util";
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { SysRoleBean } from './../bean/sysRole.bean';
import {Observable} from 'rxjs/Rx';

@Component({
    selector: 'role-modify-page',
    templateUrl: 'role-modify.html',
    styleUrls: ['role-modify.scss']
})
export class RoleModifyPage implements OnInit, OnChanges {
    validateForm: FormGroup;
    isSpinning: boolean=false;
    functions: any = [];
    data2: any=[];
    partyList: any=[];
    expandDataCache = {};
    @Input() inValue: any = [];
    data=[];
    @Output("outPut") outPut = new EventEmitter()
    //角色信息
    sysRoleBean:SysRoleBean=new SysRoleBean();
    //角色添加的权限(功能)
    funList:any=[];

    constructor(
        private fb: FormBuilder,
        private httpServcie: HttpServcie,
        private _notification: NzNotificationService
    ) {
        this.validateForm = this.fb.group({
            roleName: [null, [Validators.required]],
            roleDescribe: [null, [Validators.required]]
        });
    }

    /**
     * 选择checkbox
     * @param event
     * @param param
     */
    refreshStatus(event,param) {
        if(event){
            this.funList.push(param);
        }else{
            //如果非选中状态移除
            if(this.funList.length>0){
                this.httpServcie.removeByValue(this.funList,param);
            }
        }
    }


    ngOnInit() {
        //let partyId = JSON.parse(window.localStorage['user']).partyId;
      let userId = JSON.parse(window.localStorage['user']).id;
        Observable.forkJoin(

            //查询当前修改角色拥有的权限
            this.httpServcie.findUserFunctionByRoleId(this.functions.id),
            //查询当前登录用户拥有的权限
            this.httpServcie.findUserFunction(userId),
            //查询角色的信息
            this.httpServcie.roleFindById(this.functions.id),
            //this.httpServcie.systemRoleTypeQueryList({})
        ).subscribe(data=>{
                if(data[0].status==200){
                    let dataList:any=[];
                    dataList = data[0].data;
                    dataList.forEach(element=>{
                        this.funList.push(element.authorId);
                    });
                }
                if(data[1].status==200){
                    this.data = data[1].data;
                    this.executeArray(this.data);
                    this.data.forEach(item => {
                        this.expandDataCache[ item.authorId ] = this.convertTreeToList(item);
                    });
                }
                if(data[2].status==200){
                    this.sysRoleBean = data[2].data;
                }
                // if(data[3].status==200){
                //     //当前机构
                //     this.partyList.push({"roleTypeName":'请选择',id:""});
                //     data[3].data.list.forEach(element=>{
                //         this.partyList.push(element);
                //     });
                // }
        });

    }

    //判断是否选中
    executeArray(items) {
        items.map((item) => {
            if (this.funList.includes(item.authorId)) {
                item.checked=true;
            }
            if (item.childList) {
                this.executeArray(item.childList);
            }
        })
    }

    ngOnChanges() {
        this.functions = [];
        if (this.inValue) {
            this.functions = this.inValue;
        }
        this.data2 = this.data;
    }

    submitForm() {
        //校验是否能提交
        //没有填的标红
        for (const i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
        }
        //处理是否提交
        for (const i in this.validateForm.controls) {
            if(!this.validateForm.controls[i].valid){
                return;
            }
        }

        this.isSpinning = true;
        //修改所属机构
        if(this.funList[0]!=null){
            this.sysRoleBean.list = this.funList;
        }else{
            this.sysRoleBean.list = [];
        }

        let ob = this.httpServcie.updateRole(this.sysRoleBean).subscribe(data=>{
            this.isSpinning = false;
            if(data.status==200){
                this._notification.create('success', '成功提示', '修改成功');
                this.outPut.emit(data);
            }else{
                this._notification.create('error', '错误提示', data.message);
            }

        })

    }

    //交验
    getFormControl(name) {
        return this.validateForm.controls[name];
    }


    collapse(array, data, $event) {
        if ($event === false) {
            if (data.childList) {
                data.childList.forEach(d => {
                    const target = array.find(a => a.authorId === d.authorId);
                    target.expand = false;
                    this.collapse(array, target, false);
                });
            } else {
                return;
            }
        }
    }

    convertTreeToList(root) {
        const stack = [], array = [], hashMap = {};
        stack.push({ ...root, level: 0, expand: false });

        while (stack.length !== 0) {
            const node = stack.pop();
            this.visitNode(node, hashMap, array);
            if (node.childList) {
                for (let i = node.childList.length - 1; i >= 0; i--) {
                    stack.push({ ...node.childList[ i ], level: node.level + 1, expand: false, parent: node });
                }
            }
        }

        return array;
    }

    visitNode(node, hashMap, array) {
        if (!hashMap[ node.authorId ]) {
            hashMap[ node.authorId ] = true;
            array.push(node);
        }
    }
}
